<template>

  <!--头: 引入 CommonHead 子组件-->
  <header class="update-user-info-head">
    <CommonHead title="修改个人描述"/>
  </header>

  <!--体: 使用卡片单元格布局修改界面-->
  <section class="update-user-info-body">

    <van-cell-group inset>

      <!--个人描述: 双绑个人描述，固定5行，文本域类型，最大1024个字符，背景提示子，展示字符限制-->
      <van-field v-model="userInfo" rows="5" type="textarea"
                 maxlength="1024" placeholder="请输入个人描述，不超过1024个字符" show-word-limit/>

    </van-cell-group>

  </section>

  <!--操作区: 保存按钮-->
  <article class="operation">

    <!--按钮: 圆角，区块，小号，主要蓝，点击时触发-->
    <van-button round block size="small" type="primary" @click="updateUserInfo">保存</van-button>

  </article>

</template>

<script setup>

import CommonHead from "@/components/CommonHead";
import {UPDATE_PERSONAL} from '@/api/user';
import {useStore} from "vuex";
import router from "@/router";
import {onBeforeMount, shallowRef} from "vue";
import {showFailToast, showSuccessToast} from "vant";
import {SUCCESS} from "@/constant";

/* ==================== data ==================== */

// data: Vuex实例，直接使用useStore()会报错
let vuex = useStore();

// data: 用户主键
const userId = sessionStorage.getItem('userId');

// data: 用户个人描述，转为字符串是为了方便正则校验
let userInfo = shallowRef(router.currentRoute.value.query['userInfo'] + "");

/* ==================== method ==================== */

// method: 修改用户个人描述
async function updateUserInfo() {

  // 用户个人描述规则校验
  if (!/^[a-zA-Z0-9_-]{5,1024}$/.test(userInfo.value)) {
    showFailToast("用户描述长度在5-1024个字符");
    return;
  }

  // 异步调用修改用户信息接口
  let result = await UPDATE_PERSONAL({'userInfo': userInfo.value});
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    showSuccessToast("修改成功");
    await router.push("/Personal");
  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

/* ==================== beforeMount ==================== */

// beforeMount: DOM挂载前，判断用户是否登录
onBeforeMount(() => {
  if (!vuex.state['loginFlag']) {
    showFailToast('请先登录');
    setTimeout(() => router.push("/LoginByAccount"), 1000);
  }
});

</script>

<style scoped lang="scss">
.update-user-info-body {
  margin: 15px 0;
}

.operation{
  padding: 0 10px;
}
</style>